package com.dingdang.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dingdang.data.Result;
import com.dingdang.dto.UserDTO;
import com.dingdang.em.ResultEnum;
import com.dingdang.entity.TbGiftGoods;
import com.dingdang.mapper.TbGiftGoodsMapper;
import com.dingdang.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("selectGift")
@Api("用户选择礼品接口")
public class SelectGiftController
{

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TbGiftGoodsMapper giftGoodsMapper;

    @PostMapping
    @ApiImplicitParam(name = "giftGoodsId",value = "礼物名id",required = true,paramType = "query")
    public Result selectGoods(@RequestParam("giftGoodsId") Long giftGoodsId, HttpServletRequest request)
    {
        String token = request.getHeader("authToken");
        //获取登录态
        Claims authToken = jwtUtil.parseJwt(token);
        String subject = authToken.getSubject();
        UserDTO userDTO = JSONObject.parseObject(subject, UserDTO.class);
        //用户id
        Long uid = userDTO.getUid();
        TbGiftGoods giftGoods = giftGoodsMapper.selectGoods(uid);

            if (giftGoods.getGiftGoodsStock()<=0)
            {
                return Result.response(ResultEnum.ERROR).setData("对不起此礼物已抢空！");
            }
            LambdaUpdateWrapper<TbGiftGoods> wrapper = new LambdaUpdateWrapper();
            wrapper.set(TbGiftGoods::getGiftGoodsStock,giftGoods.getGiftGoodsStock() -1);
            giftGoodsMapper.update(null,wrapper);
        return Result.response(ResultEnum.SUCCESS).setData("恭喜您，选择成功我们会在几个工作日之内将礼物送达！");
    }
}
